package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Kidy
 * @date 2020/6/23 15:42
 */
public class Consumer01 {

    private static final String QUEUE = "hello默默";

    public static void main(String[] args) throws IOException, TimeoutException {
        //通过连接工厂来创建新的连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.237.200");
        connectionFactory.setPort(30008);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //设置虚拟机 一个mq的服务可以设置多个虚拟机,每个虚拟机就相当于一个mq
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE,true,false,false,null);

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //交换机
                String exchange = envelope.getExchange();
                //消息id
                long deliveryTag = envelope.getDeliveryTag();

                String s = new String(body,"utf-8");
                System.out.println(s);
            }
        };
        channel.basicConsume(QUEUE,true,defaultConsumer);
    }
}
